package com.getword.security.core.validate.code;

import com.getword.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
//import org.springframework.social.connect.web.HttpSessionSessionStrategy;
//import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    /**
     * 验证码校验失败处理器
     */
    private AuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 系统配置信息
     */
//    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    /**
     * 拦截的URL
     */
    private Set<String> urls = new HashSet<>();
    /**
     * spring提供的path匹配工具
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();
    /**
     * 系统配置信息
     */
    private SecurityProperties securityProperties;

    // 在所有bean被设置了属性后调动
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        System.out.println("ValidateCodeFilter的所有属性被设置完成。。。");
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getImage().getUrl(), ",");
        for (String url : configUrls) {
            urls.add(url);
        }
        urls.add("/authentication/form");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean action = false;
        for (String url : urls) {
            if (pathMatcher.match(url, request.getRequestURI())) {
                action = true;
                break;
            }
        }
        // 只处理登录请求
        if (action) {
            try {
                validate(new ServletWebRequest(request, response));
                logger.info("验证码校验通过");
            } catch (ValidateCodeException e) {
                //验证失败
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return; // 不要继续走下面的过滤器
            }
        }

        filterChain.doFilter(request, response);
    }

    protected void validate(ServletWebRequest request) throws ServletRequestBindingException {
        // 从session中拿到imageCode
        ImageCode codeInSession = (ImageCode) request.getRequest().getSession().getAttribute(ValidateCodeController.SESSION_KEY);
//        ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY);
        // 获取客户端输入的code,当前请求参数
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        if (codeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        if (codeInSession.isExpired()) {
            throw new ValidateCodeException("验证码已过期");
        }
        if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        request.getRequest().getSession().removeAttribute(ValidateCodeController.SESSION_KEY);
//        sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
    }

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
